﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BigPang.Common.GamePlay
{
    public class GameManager
    {
        static int mIdSeed = 0;

        static Dictionary<int, GameObject> mObjMap = new Dictionary<int, GameObject>();

        public static void RegisterObject(GameObject obj)
        {
            if( obj.Id == 0 )
                obj.Id = Interlocked.Increment(ref mIdSeed);

            mObjMap[obj.Id] = obj;

            obj.OnAdd();
        }

        public static void ProcessTick()
        {
            Parallel.ForEach( mObjMap, (kv) => 
            {
                kv.Value.OnProcessTick();
            });
        }

        public static List<GameObject> GetList()
        {
            List<GameObject> objList = new List<GameObject>();

            foreach (KeyValuePair<int, GameObject> kv in mObjMap)
            {
                objList.Add(kv.Value);
            }

            return objList;
        }

        public static GameObject Get(int id)
        {
            try
            {
                return mObjMap[id];
            }
            catch
            {
                return null;
            }
        }

        public static void UnregisterObject(GameObject obj)
        {
            obj.OnRemove();

            mObjMap.Remove(obj.Id);
        }
    }
}
